package main

import (
	"fmt"
	"math/rand"
	"os"
	"runtime"
	"sync"
	"sync/atomic"
	"time"

	"github.com/op/go-logging"
	"github.com/shirou/gopsutil/cpu"
	"gopkg.in/alecthomas/kingpin.v2"
)

var (
	highWater  = kingpin.Flag("highWater", "highWater").Required().Short('h').Float64()
	lowWater   = kingpin.Flag("lowWater", "lowWater").Required().Short('l').Float64()
	interval   = kingpin.Flag("interval", "interval").Required().Short('i').Int()
	total_time = kingpin.Flag("runtime", "total runtime").Required().Short('t').Int()
	log_file   = kingpin.Flag("log", "log file.").Short('g').String()
	log        = logging.MustGetLogger("cpuWatcher")
)

var n int

func init() {
	n = runtime.NumCPU()
	runtime.GOMAXPROCS(n)
}

func main() {
	kingpin.Parse()
	if *log_file == "" {
		bk := logging.NewLogBackend(os.Stderr, "", 0)
		logging.SetBackend(bk)
	} else {
		file, err := os.OpenFile(*log_file, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
		if err != nil {
			log.Errorf("open log file %s , error: ", *log_file, err)
		}
		defer file.Close()
		bk := logging.NewLogBackend(file, "", 0)
		logging.SetBackend(bk)
	}

	//lowWater
	//hightWater
	//interval
	//factor
	var wait, repeat atomic.Value
	wait.Store(8)      //8
	repeat.Store(1000) //1000
	ntf, errchan := CpuLevel(*interval, *highWater, *lowWater)
	go func() {
		for {
			select {
			case f := <-ntf:
				if f {
					CtrlCpuUsage(&wait, &repeat, true)
				} else {
					CtrlCpuUsage(&wait, &repeat, false)
				}
			}
		}
	}()
	t := time.After(time.Second * time.Duration(*total_time))
	var wg sync.WaitGroup
	wg.Add(2 * n)
	var ctrlList []chan<- interface{}
	for i := 0; i < 2*n; i++ {
		ctrlList = append(ctrlList, cost(&wait, &repeat, &wg))
	}
LOOP:
	for {
		select {
		case err := <-errchan:
			log.Error(err)
			break LOOP
		case <-t:
			break LOOP
		}
	}
	for _, i := range ctrlList {
		close(i)
	}
	wg.Wait()
}

func CtrlCpuUsage(wait, repeat *atomic.Value, ctrl bool) {
	if ctrl {
		log.Info("low usage of cpu")
		w := (*wait).Load().(int)
		(*wait).Store(w + 8) //8
		i := (*repeat).Load().(int)
		(*repeat).Store(i + 1000) //1000
	} else {
		log.Info("hign usage of cpu")
		w := (*wait).Load().(int)
		(*wait).Store(w - 8) //8
		i := (*repeat).Load().(int)
		(*repeat).Store(i - 1000) //1000
	}
}

//check at interval
//get cpu% (1-idle)
//if cpu% < low water  send true
//if cpu% > hight water  send false
func CpuLevel(interval int, highWater, lowWater float64) (<-chan bool, chan error) {
	errs := make(chan error)
	ntf := make(chan bool)
	tk := time.Tick(time.Millisecond * time.Duration(interval))
	var lastIdle, lastTotal *float64

	go func() {
		for {
			<-tk
			v, err := cpu.Times(false)
			if err != nil {
				errs <- err
				continue
			}
			if len(v) != 1 {
				errs <- fmt.Errorf("nil value when get cpu")
				continue
			}
			idle := v[0].Idle
			total := v[0].Total()
			if lastIdle != nil && lastTotal != nil {
				usage := 1 - (idle-*lastIdle)/(total-*lastTotal)
				if usage < lowWater {
					ntf <- true
				} else if usage > highWater {
					ntf <- false
				}
			}
			lastIdle = &idle
			lastTotal = &total
		}
	}()

	return ntf, errs
}

func cost(wait, repeat *atomic.Value, wg *sync.WaitGroup) chan<- interface{} {
	ctrl := make(chan interface{})
	go func() {
		var maybePi float64
	LOOP:
		for {
			if maybePi == 0 {
				maybePi = 1
			}
			select {
			case <-ctrl:
				break LOOP
			default:
				w := (*wait).Load().(int)
				<-time.After(time.Microsecond * time.Duration(w))
				for i := 0; i < (*repeat).Load().(int); i++ {
					i := rand.Intn(10000) + 1
					maybePi -= maybePi * float64(1/2*i+1)
				}
			}
		}
		wg.Done()
	}()
	return ctrl
}
